<template>
  <div id="components-form-demo-advanced-search">
    <a-form class="ant-advanced-search-form" :form="form" @submit="handleSearch">
      <a-row :gutter="24">
        <a-col
          v-for="(q,i) of queryInfo"
          :key="i"
          :span="span(q,i)"
          :style="{ display: i < count ? 'block' : 'none' }"
        >
          <HK-form-item :item="q" :dictProperties="dictProperties" :dictProperty="dictProperties[q.field]" @dateChange="valueDate"></HK-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" :style="{ textAlign: 'right' }">
          <a-button size="small" type="primary" html-type="submit">
            查询
          </a-button>

          <a-button size="small" :style="{ marginLeft: '8px' }" @click="handleReset">
            重置
          </a-button>
          <a :style="{ marginLeft: '8px', fontSize: '12px' }" @click="toggle">
            {{expandLabel}} <a-icon :type="expand ? 'up' : 'down'" />
          </a>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>
<script>
import HKFormItem from './YGFormItem.vue';
import { httpAction } from '@/utils/request.js'

export default {
    name: 'HKAdvSearch',
    props: {
      paramNo: {
        required: false,
        default: 3
      },
      queryInfo: {
        items: Array,
        required: true
      },
      dictProperties: {
        items: Object,
        default: {}
      },
    },
    data() {
      return {
        expand: false,
        url: {
          getDataBySql: '/report/config/getDataBySql'
        },
        form: this.$form.createForm(this, {
          name: 'advanced_search',
          onFieldsChange: (_, changedFields) => {
            //console.log(changedFields);
          },
          onValuesChange: (_, values) => {
            //统计有依懒的项并保存成集合
            let deps = {};
            for(let dataIndex in this.dictProperties){
              let p = this.dictProperties[dataIndex];
              if(p.dep){
                //依懒格式：@依懒字段:对应要查表的字段(空则同名)
                let tmp = p.dep.split(":");
                tmp[1] = tmp[1]||tmp[0];
                deps[tmp[1]] = {'field':tmp[0],...p,dataIndex};
              }
            }
            //console.error("Dic:",JSON.stringify(deps))
            //console.error("values:",JSON.stringify(values))
            //触发地,用外字段关联，从依懒集合中匹配可以触发的并执行
            for(let i in values){
               deps[i] && this.valueDict({value:values[i], refObj:deps[i]});
            }
          },

        }),
      };
    },
    computed: {
      count() {
        return this.expand ? this.queryInfo.length : this.paramNo;
      },
      expandLabel(){
        return this.expand ? '收起' : '展开';
      }
    },
    components:{
      HKFormItem
    },
    updated() {
      console.log('updated');
    },
    methods: {
      span(q,i) {
        let spanLast = 24/this.paramNo;
        if(q&&q.field_type==6) spanLast-=2
        if(q&&q.field_type==3 && q.mode=='group') spanLast+=(this.paramNo-2)
        if(q&&q.field_type!=3 && q.mode=='single') spanLast-=1
        return spanLast;
      },
      handleSearch(e) {
        let self = this,params = {};
        e.preventDefault();
        this.form.validateFields((error, values) => {
          if (error) {
            self.$message.warning("查询失败");
            return;
          }
          params=Object.assign({},values);
          //console.error(JSON.stringify(params))
          this.queryInfo.forEach(p=>{
            let fmt = (p.field_type == 4 ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD');
            if (p['label'].indexOf("年") != -1) fmt = 'YYYY';
            if (p['label'].indexOf("月") != -1) fmt = 'YYYY-MM';
            if (p.field_type==6) params[p.field] = params[p.field]?1:0;
            if (p.field_type==3||p.field_type==4){
               if (p.mode=='group'){
                 let begin = params[`${p.field}_begin`]
                 console.error(begin)
                 if (begin && typeof begin!="string") params[`${p.field}_begin`] = begin.format(fmt)
                 let end = params[`${p.field}_end`]
                 console.error(end)
                 if (end && typeof begin!="string") params[`${p.field}_end`] =end.format(fmt);
               }else{
                 if (params[p.field]) params[p.field] = params[`${p.field}`].format(fmt)
               }
             }
             if ($.isArray(params[`${p.field}`])) params[`${p.field}`] = params[`${p.field}`].join(",");
          })
          console.log('Received values of form: ', JSON.stringify(params));
          self.$emit('search', params);
        });

      },
      handleReset() {
        this.form.resetFields();
      },
      toggle() {
        this.expand = !this.expand;
      },
      valueDate(obj){
         this.form.setFieldsValue({
           ...obj
         });
         //this.form.getFieldsValue
      },
      valueDict(obj){
        //console.error(JSON.stringify(obj))
        let self = this;
        let condition = "1=2";
        let {value:val,refObj:{dataIndex,field,multi,param:{text,value,table}}} = obj;
        if(val) condition=`${field}='${val}'`
        let sql = `select ${text} text,${text} title,${value} [value],${value} field_name from ${table} where ${condition} group by ${text},${value} order by 1`;
        //console.error(sql)
        httpAction(this.url.getDataBySql,{sql:sql},'post').then(function (res) {
          let len = self.dictProperties[dataIndex]["options"].length;
          if(res.result)self.dictProperties[dataIndex]["options"].splice(0,len,...res.result)
          //console.error(JSON.stringify(self.dictProperties))
        })
      }
    },
    mounted(){
    }
  };
</script>
<style>
  .ant-advanced-search-form {
    padding: 24px;
    background: #fbfbfb;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
  }

  .ant-advanced-search-form .ant-form-item {
    display: flex;
  }

  .ant-advanced-search-form .ant-form-item-control-wrapper {
    flex: 1;
  }

  #components-form-demo-advanced-search .ant-form {
    max-width: none;
  }
  #components-form-demo-advanced-search .search-result-list {
    margin-top: 16px;
    border: 1px dashed #e9e9e9;
    border-radius: 6px;
    background-color: #fafafa;
    min-height: 200px;
    text-align: center;
    padding-top: 80px;
  }
  .ant-form-item-children .ant-form-item{
    padding: 0!important;
    margin: 0!important;
  }
  .check + div{
    display:none!important;
  }
  div[class^="ant-col-"]{
    padding-left: 5px!important;
    padding-right: 5px!important
  }
  .ant-row {
    margin: 1px 0 !important;
  }
  div[class="ant-col"] {
    padding-left: 0px!important;
    padding-right: 0px!important
  }
</style>